#include "simpledeviceitem.h"
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <QGraphicsTextItem>
#include <QBrush>
#include <QPen>
#include <QFont>
#include <QRectF>
#include <QSizeF>
#include <QPixmap>
#include <QGraphicsPixmapItem>
#include <QFile>

SimpleDeviceItem::SimpleDeviceItem(const QString &id, const QString &label, const QString &pixmapPath, QGraphicsItem *parent)
    : QGraphicsRectItem(parent), m_id(id)
{
    // 如果提供了图片且存在，则显示图片
    if (!pixmapPath.isEmpty() && QFile::exists(pixmapPath)) {
        QPixmap px(pixmapPath);
        if (!px.isNull()) {
            // 设为固定大小的图片显示
            const int w = 140, h = 80;
            QPixmap scaled = px.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            m_pixmapItem = new QGraphicsPixmapItem(scaled, this);
            m_pixmapItem->setOffset(-scaled.width()/2, -scaled.height()/2);
            // 将矩形作为占位，但透明以保持边框
            setRect(-scaled.width()/2, -scaled.height()/2, scaled.width(), scaled.height());
            setBrush(QBrush(Qt::lightGray));
            QPen p = pen(); p.setWidth(2); setPen(p);
            setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
            return;
        }
    }

    // 否则使用原有的矩形和文字
    setRect(-70, -30, 140, 60);
    setBrush(QBrush(Qt::lightGray));
    QPen p = pen();
    p.setWidth(2);
    setPen(p);
    setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);

    // 标签文字，居中
    QGraphicsTextItem *txt = new QGraphicsTextItem(label, this);
    QFont f = txt->font();
    f.setPointSize(10);
    f.setBold(true);
    txt->setFont(f);
    QRectF r = rect();
    QSizeF ts = txt->boundingRect().size();
    txt->setPos(r.center().x() - ts.width()/2, r.center().y() - ts.height()/2);
}

void SimpleDeviceItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    QMenu menu;
    QAction *edit = menu.addAction(tr("编辑参数"));
    QAction *curve = menu.addAction(tr("查看功率曲线"));
    QAction *act = menu.exec(event->screenPos());
    if (act == edit) emit editRequested(m_id);
    else if (act == curve) emit viewCurveRequested(m_id);
}
